1. Construction


In [1]:
# create an empty dictionary 
empty_dict = {}
empty_dict = dict()

# create a dictionary with content
family = {'dad':'homer', 'mom':'marge', 'size':6}
faimly = dict(dad='homer', mom='marge', size=6)
family


Out[1]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}

In [1]:
# convert a liist of tuples into a dictionary
list_of_tuples = [('dad','homer'), ('mom','marge'), ('size',6)]
family=dict(list_of_tuples)
family


Out[1]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}

In [3]:
# creating a dictionary from a sequence of keys (no values created)
seq = ('name', 'age', 'sex')
d = dict.fromkeys(seq)
d


Out[3]:
{'age': None, 'name': None, 'sex': None}

In [7]:
# creating a dictionary from a sequence of keys and a value to use as the default value
d = dict.fromkeys(seq, 10)
d


Out[7]:
{'age': 10, 'name': 10, 'sex': 10}

2. Getting Data


In [3]:
# pass a key ti return its value
family['dad']


Out[3]:
'homer'

In [4]:
# return number of key-value pairs
len(family)


Out[4]:
3

In [5]:
# check if key exists in dictionary
'mom' in family


Out[5]:
True

In [6]:
# only keys, not values, are checked
'marge' in family


Out[6]:
False

In [7]:
# returns an iterable view of keys
family.keys()


Out[7]:
dict_keys(['dad', 'mom', 'size'])

In [8]:
# returns an iterable view of values
family.values()


Out[8]:
dict_values(['homer', 'marge', 6])

In [16]:
# returns an iterable view of key-value pairs
family.items()


Out[16]:
dict_items([('mom', 'marge'), ('size', 6), ('kids', ['bart', 'lisa'])])

3. Safer Access With Get


In [17]:
# equivalent to a dictionary lookup
family.get('mom')


Out[17]:
'marge'

In [18]:
# this would throw an error since the key does not exist
# family['grandma']

In [20]:
# return None if not found
family.get('grandma')

In [22]:
# provide a default return value if not found
family.get('grandma', 'not found')


Out[22]:
'not found'

In [23]:
# accesss an element within a list inside a dictionary
family['kids'][0]


Out[23]:
'bart'

4. Adding and Changing Data


In [11]:
# edit an existing entry
family['cat'] = 'snowball'
family


Out[11]:
{'cat': 'snowball', 'dad': 'homer', 'mom': 'marge', 'size': 6}

In [12]:
# edit an existing entry
family['cat'] = 'snowball ii'
family


Out[12]:
{'cat': 'snowball ii', 'dad': 'homer', 'mom': 'marge', 'size': 6}

In [13]:
# delete an entry
del family['cat']
family


Out[13]:
{'dad': 'homer', 'mom': 'marge', 'size': 6}

In [14]:
# dictionary value can be a list
family['kids']=['bart','lisa']
family


Out[14]:
{'dad': 'homer', 'kids': ['bart', 'lisa'], 'mom': 'marge', 'size': 6}

In [15]:
# remove an entry and return the value
family.pop('dad')


Out[15]:
'homer'

In [24]:
# add multiple-entries
family.update({'baby':'maggie', 'mom':'Marge', 'grandpa':'abe'})
family


Out[24]:
{'baby': 'maggie',
 'grandpa': 'abe',
 'kids': ['bart', 'lisa'],
 'mom': 'Marge',
 'size': 6}

In [25]:
family['kids'].remove('lisa')
family


Out[25]:
{'baby': 'maggie',
 'grandpa': 'abe',
 'kids': ['bart'],
 'mom': 'Marge',
 'size': 6}

5. String Substitution With a Dictionary


In [28]:
# replaces %(baby)s with the result of looking up 'baby' in family
'youngest child is %(baby)s' % family


Out[28]:
'youngest child is maggie'

6. Default Elements

Ways to get a default element add to the dictionary on first access


In [29]:
# using defaultdict 
from collections import defaultdict

d=defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(3)
d


Out[29]:
defaultdict(list, {'a': [1, 2], 'b': [3]})

In [1]:
# using setdefault
d={}
d.setdefault('a',[]).append(1)
d.setdefault('a',[]).append(2)
d.setdefault('b',[]).append(3)
d


Out[1]:
{'a': [1, 2], 'b': [3]}

7. Set Operations On Keys and Items


In [2]:
a = {
'x' : 1,
'y' : 2,
'z' : 3
}

b = {
'w' : 10,
'x' : 11,
'y' : 2
}

# Find keys in common
a.keys() & b.keys() # { 'x', 'y' }


Out[2]:
{('y', 2)}

In [3]:
# Find keys in a that are not in b
a.keys() - b.keys() # { 'z' }


Out[3]:
{'z'}

In [4]:
# Find (key,value) pairs in common
a.items() & b.items() # { ('y', 2) }


Out[4]:
{('y', 2)}

These kinds of operations can also be used to alter or filter dictionary contents. For example, suppose you want to make a new dictionary with selected keys removed. Here is some sample code using a dictionary comprehension:


In [5]:
{key:a[key] for key in a.keys() - {'z', 'w'}}


Out[5]:
{'x': 1, 'y': 2}

8. Dictionary Comprehensions


In [1]:
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}

# Make a dictionary of all prices over 200
{ key:value for key, value in prices.items() if value > 200 }


Out[1]:
{'AAPL': 612.78, 'IBM': 205.55}

In [2]:
# Make a dictionary of tech stocks
tech_names = { 'AAPL', 'IBM', 'HPQ', 'MSFT' }
{ key:value for key,value in prices.items() if key in tech_names }


Out[2]:
{'AAPL': 612.78, 'HPQ': 37.2, 'IBM': 205.55}